import { SettingDrawer } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser, getmeuns } from './services/ant-design-pro/api';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
const isDev = process.env.NODE_ENV === 'development';
import { BasicLayoutProps, Settings as LayoutSettings } from '@ant-design/pro-layout';
import * as Icon from '@ant-design/icons';
import { message } from 'antd';
import React from 'react';
import unAccessible from './pages/403';
const loginPath = '/user/login';
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

//初始加载
export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  }; // 如果是登录页面，不执行

  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }

  return {
    fetchUserInfo,
    settings: {},
  };
} // ProLayout 支持的api https://procomponents.ant.design/components/layout
const loopMenuItem = (menus) =>
  menus?.map(({ icon, routes, ...item }) => {
    if (typeof icon != 'undefined' && Icon[icon] != undefined) {
      return {
        ...item,
        icon: icon && React.createElement(Icon[icon]),
        routes: routes && loopMenuItem(routes),
      };
    } else {
      return {
        ...item,
        routes: routes && loopMenuItem(routes),
      };
    }
  });
export const request = {
  errorHandler: (error) => {
    const { response } = error;
    if (!response) {
      message.error({
        description: '您的网络发生异常，无法连接服务器',
        message: '网络异常',
      });
    }
    throw error;
  },
  //prefix: `${DOMAIN}`,
  requestInterceptors: [
    (url, options) => {
      // eslint-disable-next-line no-param-reassign
      url = decodeURI(encodeURI(url).replace(/%E2%80%8B/g, ''));
      const newOptions = { ...options };
      const auttoken = localStorage.getItem('token');
      const userid = localStorage.getItem('userid');
      newOptions.headers = {
        ...newOptions.headers,
        userid: userid,
        authorization: 'Bearer  ' + auttoken,
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
      };
      return { url, options: newOptions };
    },
  ],
  responseInterceptors: [
    (res, option) => {
      if (res.status == 401) {

        if (history.location.pathname !== loginPath && history.location.pathname !== '/') {
          message.error('用户没有权限！');
        }
        history.push(loginPath);
      } else if (res.status == 403) {

        history.push('403');
      }
      return res;
    },
  ],
};

var menuList = [
  {
    path: '/welcome',
    name: 'welcome',
    icon: 'smile',
    hideInMenu: true,
    component: './Welcome',
  },
];
export const layout = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    menu: {
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: initialState,
      locale: false,
      request: async (params, defaultMenuData) => {
        return loopMenuItem([...menuList, ...initialState?.currentUser?.menuList]);
      },
    },

    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history; // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },

    // 自定义 403 页面
    //unAccessible: <div><unAccessible /></div>,
    // 增加一个 loading 的状态
    // childrenRender: (children, props) => {
    //   // if (initialState?.loading) return <PageLoading />;
    //   return (
    //     <>
    //       {children}
    //       {!props.location?.pathname?.includes('/login') && (
    //         <SettingDrawer
    //           enableDarkTheme
    //           settings={initialState?.settings}
    //           onSettingChange={(settings) => {
    //             setInitialState((preInitialState) => ({ ...preInitialState, settings }));
    //           }}
    //         />
    //       )}
    //     </>
    //   );
    // },
    ...initialState?.settings,
  };
};
